package com.wswy.wzcx.widget;


import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Build.VERSION;
import android.support.annotation.Keep;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.blankj.utilcode.util.DeviceUtils;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.api.ProgressDialogObserver;
import com.che.libcommon.utils.JsonKit;
import com.che.libcommon.utils.RxBus;
import com.che.libcommon.utils.ToastUtils;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.model.pay.PayStyleModel;
import com.wswy.wzcx.model.wzdb.WzdbCreateResp;
import com.wswy.wzcx.module.ChannelManager;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.activity.ModuleActivity;
import com.wswy.wzcx.ui.activity.UpLoadActivity;
import com.wswy.wzcx.ui.data.OrderNoNeedParam;
import com.wswy.wzcx.ui.data.PayResult;
import com.wswy.wzcx.ui.fkdj.FinePaymentActivity;
import com.wswy.wzcx.ui.fragment.WZDBFragment;
import com.wswy.wzcx.ui.wzdb.WZDBSubmitCertActivity;
import com.wswy.wzcx.utils.ShareDialog;
import com.wswy.wzcx.utils.ShareHelper;
import com.wswy.wzcx.utils.Tools;

import java.lang.ref.WeakReference;
import java.util.List;

import org.json.JSONObject;

/**
 * Created by wangduheng26 on 2018/2/7.
 * wangduheng26@gmail.com
 */
@Keep
public class JCInterface {
    private WeakReference<Activity> mActRef;

    public JCInterface(Activity activity) {
        mActRef = new WeakReference<>(activity);
    }

    /**
     * 系统版本
     *
     * @return
     */
    @JavascriptInterface
    public String onGetOs() {
        return "ANDROID";
    }

    @JavascriptInterface
    public String getAppInfo() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("platform", "android");
            jsonObject.putOpt("platformVersion", VERSION.SDK_INT);
            jsonObject.putOpt("appVersion", BuildConfig.VERSION_CODE);
            jsonObject.putOpt("appChannel", ChannelManager.getChannel());
            jsonObject.putOpt("id", BuildConfig.APPLICATION_ID);


            JSONObject jsonProduct = new JSONObject();


            jsonObject.putOpt("product", jsonProduct);

            jsonProduct.putOpt("manufacturer", Build.MANUFACTURER);
            jsonProduct.putOpt("name", Build.PRODUCT);
            jsonProduct.putOpt("brand", Build.BRAND);
            jsonProduct.putOpt("model", Build.MODEL);
            jsonProduct.putOpt("device", Build.DEVICE);

            jsonProduct.put("network", Tools.getNetWork());
            jsonProduct.put("imei", Tools.getIMEI());
            jsonProduct.put("phone", Tools.getPhoneNumber());
            jsonProduct.put("android_id", DeviceUtils.getAndroidID());

        } catch (Throwable e) {
            e.printStackTrace();
        }

        return jsonObject.toString();
    }

    /**
     * 关闭页面
     */
    @JavascriptInterface
    public void onBack() {
        if (mActRef != null && mActRef.get() != null) {
            Activity activity = mActRef.get();
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    /**
     * 复制
     *
     * @param text
     */
    @JavascriptInterface
    public void clipText(String text) {
        if (mActRef != null && mActRef.get() != null) {
            Activity activity = mActRef.get();
            if (activity != null && !activity.isFinishing()) {


                ClipboardManager clipboardManager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
                clipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showText("已复制");
                    }
                });
            }
        }
    }

    /**
     * 分享app
     */
    @JavascriptInterface
    public void shareBack() {
        final Activity activity;
        if (mActRef != null && (activity = mActRef.get()) != null) {
            if (!activity.isFinishing()) {
                ShareHelper.shareApp(activity);
                StatTools.sendClick(activity, StatisticsId.mine_order_done_share);
            }
        }
    }

    /**
     * 分享 url
     *
     * @param json
     */
    @JavascriptInterface
    public void shareUrl(String json) {
//        {
//            "title":"标题",
//            "desc":"描述",
//            "url":"url",
//            "icon":"右边icon"
//        }

        try {

            JSONObject jsonObject = new JSONObject(json);
            final String title = jsonObject.optString("title");
            final String desc = jsonObject.optString("desc");
            final String url = jsonObject.optString("url");
            final String icon = jsonObject.optString("icon");

            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(url)) {
                return;
            }
            final Activity activity = getActivity();

            if (activity != null) {

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        Activity act = getActivity();
                        if (act != null) {

                            new ShareDialog(act, new ShareDialog.OnChooseShareTypeCallback() {
                                @Override
                                public void onChooseType(int shareType) {
                                    ShareHelper.shareUrl(AppContext
                                                    .getContext(), shareType, url, title,
                                            desc, icon);
                                }

                            }).show();

                        }

                    }
                });

            }

        } catch (Throwable e) {
            e.printStackTrace();
        }


    }

    @JavascriptInterface
    public void notifyPayment(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            int type = jsonObject.optInt("type");
            boolean paySuccess = jsonObject.optBoolean("success", false);
            String msg = jsonObject.optString("msg");
            //支付处理
//        if (type == PayStyleModel.ALIPAY_CHECAR.getCode()){
//          String errCode = paySuccess?"9000":"-1";
//          RxBus.getDefault().postWithCode(InternalMsgCode.CODE_PAY_RESULT, PayResult.buildFromAlipay(errCode));
//        }else if (type == PayStyleModel.WECHAT_CHECAR.getCode()){
//          int errCode  = paySuccess?0:-1;
//          RxBus.getDefault().postWithCode(InternalMsgCode.CODE_PAY_RESULT, PayResult.buildFromWechat(errCode));
//        }
            Activity activity = getActivity();
            if (activity != null) {
                activity.finish();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动页面
     */
    @JavascriptInterface
    public void launchPage(String json) {
//        {
//            "type":1,
//            "targetUrl":""
//        }
//        type 类型，0-原生，1-web，2-推啊广告，3-小程序

        try {

            JSONObject jsonObject = new JSONObject(json);
            int type = jsonObject.optInt("type", -1);
            if (type != -1) {
                String targetUrl = jsonObject.optString("targetUrl");

                Activity activity = getActivity();
                if (activity != null) {
                    RouterUtils.startTarget(activity, type, targetUrl);
                }
            }

        } catch (Throwable e) {
            e.printStackTrace();
        }

    }

    /**
     * 补充资料
     *
     * @param orderNo
     */
    @JavascriptInterface
    public void supplementalBack(final String orderNo) {
        final Activity activity;
        if (mActRef != null && (activity = mActRef.get()) != null) {
            if (!activity.isFinishing()) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        subParams(activity, orderNo);
                    }
                });


            }
        }
    }


    /**
     * 违章代办
     *
     * @return
     */
    @JavascriptInterface
    public void illegalCommissionback() {
        final Activity activity;
        if (mActRef != null && (activity = mActRef.get()) != null) {
            if (!activity.isFinishing()) {
                activity.runOnUiThread(() -> activity.startActivity(ModuleActivity.getTargetIntent(activity, WZDBFragment.TAG)));
            }
        }
    }

    /**
     * 罚单代缴
     *
     * @return
     */
    @JavascriptInterface
    public void ticketpaymentback() {
        final Activity activity;
        if (mActRef != null && (activity = mActRef.get()) != null) {
            if (!activity.isFinishing()) {
                activity.runOnUiThread(() -> activity.startActivity(new Intent(activity,FinePaymentActivity.class)));
            }
        }
    }

    @JavascriptInterface
    public String getUserInfo() {
        if (DataCenter.get().hasLogin()) {
            return JsonKit.GSON.toJson(DataCenter.get().getUserMode());
        }
        return null;
    }


    private void subParams(final Context context, final String orderNo) {
        Api.get().fetchOrderNeedParams(orderNo)
                .subscribe(new ProgressDialogObserver<WzdbCreateResp>(context) {
                    @Override
                    protected void onApiResult(@Nullable WzdbCreateResp orderNoNeedParams) {
                        if (orderNoNeedParams != null) {
//                        OrderNoNeedParam[] params = new OrderNoNeedParam[orderNoNeedParams.size()];
//                        params = orderNoNeedParams.toArray(params);
//                        UpLoadActivity.Companion.startUploadPage(context,orderNo,params);
                            try {
                                WZDBSubmitCertActivity.Companion.startUpload(context, orderNo, orderNoNeedParams.getList(), orderNoNeedParams.getInfo());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }

                    @Override
                    protected void onApiError(@Nullable BaseResult result) {
                        toastErrorMsg(result);
                    }
                });
    }


    private @Nullable
    Activity getActivity() {
        final Activity activity;
        if (mActRef != null && (activity = mActRef.get()) != null) {
            if (!activity.isFinishing()) {
                return activity;
            }
        }
        return null;
    }
}
